//
//  WmcRemarkVM.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/4/11.
//

import RxRelay
import UIKit

class WmcRemarkVM: WmcBaseVM {
    /// 水印备注文字
    var remarkText: String?

    /// 备注历史记录
    let remarkHistoryRelay: BehaviorRelay<[WmcRemarkHistoryModel]> = .init(value: [])

    /// 提交备注信息
    let submitRemarkRelay: PublishRelay<String> = .init()

    /// 加载数据
    func loadData() {
        WmcRemarkHistoryDBManager.searchRemarkHistory() { [weak self] list in
            guard let weakSelf = self else { return }
            weakSelf.remarkHistoryRelay.accept(list)
        }
    }

    /// 提交备注数据
    func submitRemark(_ remark: String?) {
        guard let remark = remark else { return }
        if !remark.isEmpty {
            WmcRemarkHistoryDBManager.insertRemark(remark) { [weak self] result in
                guard let weakSelf = self else { return }
                if result { // 插入成功
                    weakSelf.submitRemarkRelay.accept(remark)
                }
            }
        }else{
            submitRemarkRelay.accept(remark)
        }
    }

    /// 删除备注数据
    func deleteRemark(_ indexPath: IndexPath, model: WmcRemarkHistoryModel) {
        // 删除数据
        for (idx, model) in remarkHistoryRelay.value.enumerated() {
            if idx == indexPath.row { // 寻找到索引
                WmcRemarkHistoryDBManager.deleteRemarkHistory(id: model.id)
                break
            }
        }
        var newList: [WmcRemarkHistoryModel] = remarkHistoryRelay.value
        newList.remove(at: indexPath.row)
        remarkHistoryRelay.accept(newList)
    }
}
